const Koa = require('koa');
const Router = require('koa-router');
const devices = require('puppeteer/lib/cjs/puppeteer/common/DeviceDescriptors');
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const OSS = require('ali-oss')
const config = require('./config');

const app = new Koa();
const router = new Router();

const print = async (url, isMobile = false, isFullscreen = false, pWidth = 1920, pHeight = 1080) => {
    const browser = await puppeteer.launch({ headless: true });

    const page = await browser.newPage();
    if (isMobile) {
        await page.emulate(devices['devicesMap']['iPhone X']);
    }
    else {
        page.setViewport({
            width: pWidth,
            height: pHeight
        });
    }
    if (url) {
        try {
            await page.goto(url);
        }
        catch (e) {
            console.log(e);
        }

        let xhwcbRoot = path.join(path.resolve("./"), "xhwcb_screenshot");
        if (!fs.existsSync(xhwcbRoot)) {
            try {
                fs.mkdirSync(xhwcbRoot);
            }
            catch (e) {
                console.log(e);
            }
        }

        filename = uuidv4() + ".png"
        filepath = path.join(xhwcbRoot, filename);

        try {
            await page.screenshot({
                path: filepath,
                fullPage: isFullscreen
            });
            console.log("Screenshot of success! :" + filepath);
        }
        catch (e) {
            console.log(e);
        }
        finally {
            await page.close();
            await browser.close();
        }

        await put(filename, filepath);
        fs.unlink(filepath, function (err) {
            if (err) {
                console.log(err);
            }
        });
        return filename;
    }
}

async function put(filename, filepath) {
    const client = new OSS(config.oss);
    try {
        let result = await client.put(filename, filepath);
        console.log("Upload successful!");
    } catch (e) {
        console.log(e);
    }
}

router.get("/screenshot", async (ctx) => {
    let url = ctx.query.u;
    let isMobile = (ctx.query.m) ? ctx.query.m : false;
    let isFullscreen = (ctx.query.s) ? ctx.query.s : false;
    let width = (ctx.query.w) ? ctx.query.w : 1920;
    let height = (ctx.query.h) ? ctx.query.h : 1080;

    console.log("Target website URL: " + url);
    let filename = await print(url, isMobile, isFullscreen, width, height);
    let ret = {
        ossUrl: filename
    };
    ctx.body = ret;
});

app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
